package com.eagle.security.util;

import java.net.Inet4Address;
import java.net.InetAddress;
import java.net.UnknownHostException;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang.StringUtils;

/**
 * 
 * 
 * 获取客户端IP工具类 <br/>
 * 
 * create @ 2011-2-22 上午09:16:53 <br/>
 * 
 * @author Yuan Zhengwen
 * @version 1.0.0
 */
public class IpUtils {

	public static String getRemoteIpAddr(HttpServletRequest request) {
		String ip = request.getHeader("x-forwarded-for");
		if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
			ip = request.getHeader("Proxy-Client-IP");
		}
		if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
			ip = request.getHeader("WL-Proxy-Client-IP");
		}
		if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
			ip = request.getRemoteAddr();
		}

		if ("127.0.0.1".equals(ip)) {
			try {
				InetAddress address = Inet4Address.getLocalHost();
				ip = address.getHostAddress();
			} catch (UnknownHostException e) {
			}
		}

		return StringUtils.isBlank(ip) ? "<UNKOWN>" : ip;
	}

	public static String getHostIpAddr(HttpServletRequest request) {
		return request.getLocalAddr();
	}
}
